'''
asyncio   a醒k io
1、 同步  拿到所有章节的cid
2、 异步  下载所有的文章内容
'''
import asyncio
import sys

import aiofiles as aiofiles
import aiohttp
import requests
import json


async def aiodownload(cid, b_id, title):
    data = {
        "book_id": b_id,
        "cid": f"{b_id}|{cid}",    #"4306063500|11348571"
        "need_bookinfo": 1
    }
    data = json.dumps(data)
    url = f"https://dushu.baidu.com/api/pc/getCatalog?data={data}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            dic = await resp.json()
            print(dic)
            # 原本这样可以的  现在网站返回内容变了   {'errno': 0, 'data': {'novel': {'book_id': '4306063500', 'items': [{'title': '第一回 灵根育孕源流出 心性修持大道生', 'price_status': '0', 'cid': '11348571'}, {'title': '第二回 悟彻菩提真妙理 断魔归本合元神', 'price_status': '0', 'cid': '11348572'}
            # async with aiofiles.open(title, mode="w", encoding="utf-8") as f:  # aiofiles是异步的，所以需要下一行 写await
            #     await f.write(dic['data']['novel']['content'])  # 把小说内容分写出 找不到content


async def getCatalog(url):
    resp = requests.get(url)
    # print(resp.json())  # resp.text 获取的是所有，但我想获取的只有cid
    dic = resp.json()
    tasks = []
    for item in dic['data']['novel']['items']:  ## item 对应每一个章节的名称和cid
        title = "txt/" + item['title'] + ".txt"
        cid = item['cid']
        # 准备异步任务
        tasks.append(aiodownload(cid, b_id, title))
    await asyncio.wait(tasks)
    # asyncio.run(asyncio.wait(tasks)) 如果方法不用 async 修饰，那么就要用这一行


if __name__ == '__main__':
    b_id = "4306063500"
    url = 'https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"' + b_id + '"}'
    # getCatalog(url)
    asyncio.run(getCatalog(url))
